package com.jmda.platform.commom.util;

import com.jmda.platform.commom.SpringContextUtil;
import com.jmda.platform.database.DataBaseService;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BlobUtil {
    //从数据库获取二进制大对象
    public static List<String> getBlob(String SQL) {
        List<String> list = new ArrayList<>();
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            DataBaseService db = SpringContextUtil.getBean(DataBaseService.class);
            conn = db.getConnection();//c3p0连接池
            stmt = conn.prepareStatement(SQL);//SQL: select info from table1 (其中info字段是blob类型)
            rs = stmt.executeQuery();
            while (rs.next()) {
                InputStream in = rs.getBinaryStream(1);
                ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                byte[] data = new byte[4096];
                int count = -1;
                while ((count = in.read(data, 0, 4096)) != -1)
                    outStream.write(data, 0, count);

                data = null;
                String result = new String(outStream.toByteArray(), "utf-8");
                list.add(result);
            }

            return list;
        } catch (SQLException sqle) {
            sqle.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                conn.close();
                stmt.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }
}
